<template>
  <div
    v-loading="isLoading"
    class="panel-data"
  >
    <div class="content">
      <el-form
        ref="form"
        class="prop-form"
        label-position="right"
        :model="form"
        :rules="rules"
        label-width="93px"
      >
        <panel-data
          ref="panelDataCommon"
          :config="config"
          :widget-instance-id="widgetInstanceId"
          :data-source-type-options="dataSourceTypeOptions"
          :dataForm="form"
          :is-aurora="isAurora"
        >
          <template #dataPicker>
            <el-button
              plain
              class="btn-sure mb10"
              type="primary"
              size="default"
              icon="Plus"
              :disabled="form.apis.length > 7"
              @click.stop="addAPI()"
            >
              {{ $demoi18n('panelData.commonX.addApi') }}
            </el-button>

            <el-table
              class="config-panel-table"
              :data="form.apis"
              :row-style="{ height: '25px' }"
              :header-row-style="{ height: '25px' }"
              :header-cell-style="{ lineHeight: '15px' }"
            >
              <el-table-column :label="$demoi18n('panel.tab.data')">
                <template #default="scope">
                  <!-- 数据源类型  dataSourceType -->
                  <VsFormItem
                    :label="$demoi18n('panel.label.dataSourceType')"
                    :prop="`apis[${scope.$index}].dataSourceType`"
                    :rules="
                      generateRules({
                        label: $demoi18n('panel.label.dataSourceType'),
                      })
                    "
                  >
                    <el-select
                      v-model="scope.row.dataSourceType"
                      :class="'panel-data-select-' + xvueTheme"
                      :popper-class="'select-poper-' + xvueTheme"
                      :placeholder="$demoi18n('word.plsSelect')"
                      size="default"
                      @change="dataSourceTypeChange(scope.row)"
                      @focus="setMaxWidth"
                    >
                      <el-option
                        v-for="item in dataSourceTypeOptions"
                        :key="item.value"
                        class="panel-data-select-option"
                        :label="item.label"
                        :value="item.value"
                        :disabled="item.disabled"
                        :style="selectStyle"
                      ></el-option>
                    </el-select>
                  </VsFormItem>
                  <!-- xMiner数据源 dataSource/dataSourceList -->
                  <VsFormItem
                    v-if="scope.row.dataSourceType === XMINER"
                    :label="$demoi18n('panel.label.selectDataSource')"
                    :prop="`apis[${scope.$index}].dataSource`"
                    :rules="
                      generateRules({
                        label: $demoi18n('panel.label.selectDataSource'),
                      })
                    "
                  >
                    <el-select
                      v-model="scope.row.dataSource"
                      :class="'panel-data-select-' + xvueTheme"
                      :popper-class="'select-poper-' + xvueTheme"
                      filterable
                      :placeholder="$demoi18n('word.plsSelect')"
                      size="default"
                      @visible-change="setTagTitle($event)"
                      @change="dataSourceChange(scope.row)"
                      @focus="setMaxWidth"
                    >
                      <el-option
                        v-for="item in dataSourceList[scope.row.dataSourceType]"
                        :key="item.id"
                        class="panel-data-select-option"
                        :label="item.option_label"
                        :value="item.option_value"
                        :style="selectStyle"
                      ></el-option>
                    </el-select>
                  </VsFormItem>
                  <!-- xMinerAPI apiCode/apiLists -->
                  <VsFormItem
                    v-if="scope.row.dataSourceType === XMINER"
                    :label="$demoi18n('panel.label.selectApi')"
                    :prop="`apis[${scope.$index}].apiCode`"
                    :rules="
                      generateRules({
                        label: $demoi18n('panel.label.selectApi'),
                      })
                    "
                  >
                    <XMinerApiList
                      v-model:value="scope.row.apiCode"
                      :api-list="apiLists[scope.row.dataSource]"
                      @change="apiListChange(scope.row)"
                      @visible-change="setTagTitle($event)"
                    />
                  </VsFormItem>

                  <!-- xTag数据包 dataPackage/dataSourceList -->
                  <VsFormItem
                    v-if="scope.row.dataSourceType === XTAG"
                    :label="$demoi18n('panelData.label.xtagDataPackage')"
                    :prop="`apis[${scope.$index}].dataPackage`"
                    :rules="
                      generateRules({
                        label: $demoi18n('panelData.label.xtagDataPackage'),
                      })
                    "
                  >
                    <el-select
                      v-model="scope.row.dataPackage"
                      :class="'panel-data-select-' + xvueTheme"
                      :popper-class="'select-poper-' + xvueTheme"
                      filterable
                      :placeholder="$demoi18n('word.plsSelect')"
                      size="default"
                      @visible-change="setTagTitle($event)"
                      @focus="setMaxWidth"
                      @change="dataPackageChange(scope.row)"
                    >
                      <el-option
                        v-for="item in dataSourceList[scope.row.dataSourceType]"
                        :key="item.id"
                        class="panel-data-select-option"
                        :label="item.option_label"
                        :value="item.option_value"
                        :style="selectStyle"
                      ></el-option>
                    </el-select>
                  </VsFormItem>
                  <!-- xTag数据表 dataTable/apiLists -->
                  <VsFormItem
                    v-if="scope.row.dataSourceType === XTAG"
                    :label="$demoi18n('panelData.label.xtagDataTable')"
                    :prop="`apis[${scope.$index}].dataTable`"
                    :rules="
                      generateRules({
                        label: $demoi18n('panelData.label.xtagDataTable'),
                      })
                    "
                  >
                    <el-select
                      v-model="scope.row.dataTable"
                      class="xtag-dataTable-select"
                      :class="'panel-data-select-' + xvueTheme"
                      :popper-class="'select-poper-' + xvueTheme"
                      filterable
                      :placeholder="$demoi18n('word.plsSelect')"
                      size="default"
                      @visible-change="setTagTitle($event)"
                      @focus="setMaxWidth"
                      @change="dataTableChange(scope.row)"
                    >
                      <el-option
                        v-for="item in apiLists[scope.row.dataPackage]"
                        :key="item.id"
                        class="panel-data-select-option"
                        :label="item.option_label"
                        :value="item.option_value"
                        :style="selectStyle"
                      ></el-option>
                    </el-select>
                    <el-button
                      v-if="scope.row.dataTable"
                      class="btn-preview"
                      size="default"
                      @click="showPreview(scope.row)"
                    >{{ $demoi18n('panelData.btn.preview') }}</el-button>
                  </VsFormItem>
                </template>
              </el-table-column>

              <el-table-column
                :label="$demoi18n('word.operation')"
                width="40"
              >
                <template #default="scope">
                  <el-button
                    icon="Delete"
                    :link="true"
                    type="primary"
                    :disabled="form.apis.length === 1"
                    @click.stop="deleteAPI(scope)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </template>
          <template #dataMapping>
            <el-table
              v-for="(tableItem, tableIndex) in form.datas"
              :key="tableIndex"
              class="config-panel-table form-datas mapping-table"
              :data="tableItem"
              style="width: 100%"
              size="default"
            >
              <el-table-column
                prop="field"
                :label="$demoi18n('panel.commonX.axis')"
                width="51"
              ></el-table-column>
              <el-table-column
                :label="$demoi18n('panelData.mapping.mapping')"
                min-width="70"
              >
                <template #default="scope">
                  <span
                    v-if="!scope.row.skipVerification"
                    class="mapping-scope"
                  >*</span>
                  <VsFormItem
                    :prop="`datas[${tableIndex}][${scope.$index}].mapping`"
                    :rules="
                      genRequireRule({
                        required: !scope.row.skipVerification,
                        label: scope.row.explain,
                      })
                    "
                  >
                    <el-select
                      v-if="scope.row.field === 'api'"
                      v-model="scope.row.mapping"
                      :class="'panel-data-select-' + xvueTheme"
                      :popper-class="'select-poper-' + xvueTheme"
                      filterable
                      clearable
                      placeholder
                      size="default"
                      @focus="setXtagMaxWidth"
                      @visible-change="setTagTitle($event)"
                      @change="optionxTagChange(scope.row, tableItem, tableIndex)"
                    >
                      <el-option
                        v-for="apiItem in apis"
                        :key="apiItem.id"
                        class="panel-data-select-option"
                        :label="apiItem.apiName"
                        :value="apiItem.apiCode"
                        :style="selectStyle"
                      ></el-option>
                    </el-select>
                    <el-select
                      v-else
                      v-model="scope.row.mapping"
                      :class="'panel-data-select-' + xvueTheme"
                      :popper-class="'select-poper-' + xvueTheme"
                      filterable
                      clearable
                      placeholder
                      size="default"
                      @focus="setXtagMaxWidth"
                      @visible-change="setTagTitle($event)"
                      @change="optionxTagChange(scope.row, tableItem, tableIndex)"
                    >
                      <el-option
                        v-for="item in mappingOptionsFinal[tableItem[0].mapping]"
                        :key="item.id"
                        class="panel-data-select-option"
                        :label="item.option_label"
                        :value="item.option_value"
                        :style="selectxTagStyle"
                      >
                        <div
                          v-if="item.type && item.type === 'add'"
                          @click.stop="optionxTagClick(item, scope, tableItem, tableIndex)"
                        >
                          <span class="select-option-slot-icon">
                            <el-button
                              :link="true"
                              type="primary"
                              class="select-icon"
                            >
                              <el-icon><Plus /></el-icon>
                            </el-button>
                          </span>
                          <span
                            class="select-option-slot-text"
                            :style="{ width: `${xTagTextWidth}px` }"
                          >&nbsp;{{ item.option_label }}</span>
                        </div>
                        <div v-else-if="item.type && item.type === 'edit'">
                          <span
                            class="select-option-slot-icon select-option-slot-icon-edit"
                            :title="$demoi18n('btn.edit')"
                            @click.stop="optionxTagClick(item, scope, tableItem, tableIndex)"
                          >
                            <el-button
                              :link="true"
                              type="primary"
                              class="select-icon"
                              icon="EditPen"
                            >
                            </el-button>
                          </span>
                          <span
                            class="select-option-slot-text"
                            :style="{ width: `${xTagTextWidth}px` }"
                          >{{
                            item.option_label
                          }}</span>
                        </div>
                        <div v-else>
                          <span>{{ item.option_label }}</span>
                        </div>
                      </el-option>
                    </el-select>
                  </VsFormItem>
                </template>
              </el-table-column>
              <el-table-column
                prop="commonX"
                :label="$demoi18n('panelData.commonX.CommonXaxis')"
                width="60"
              >
                <template #default="scope">
                  <el-checkbox
                    v-if="scope.row.field === 'x'"
                    v-model="scope.row.isCheck"
                    size="default"
                    @change="isCheckChange(scope)"
                  ></el-checkbox>
                </template>
              </el-table-column>
              <el-table-column
                prop="explain"
                :label="$demoi18n('panel.explain')"
                min-width="36"
              ></el-table-column>
            </el-table>
          </template>
        </panel-data>
      </el-form>
    </div>
    <!-- 自定义计算弹出窗 -->
    <CustomCalculation
      ref="myCustomCalculation"
      :widget-instance-id="widgetInstanceId"
      :index="customCalculationIndex"
      :code="customCalculationCode"
      :type="customCalculationType"
      :title="customCalculationTitle"
      :calc-list="customCalculationParams.calcList"
      :table-name="customCalculationParams.tableName"
      :field-arr="customCalculationParams.fieldArr"
    />

    <FlatWideTable
      ref="myFlatWideTable"
      :widget-instance-id="widgetInstanceId"
      :package-code="flatWideTableParams.packageCode"
      :table-name="flatWideTableParams.tableName"
      :field-list="flatWideTableParams.fieldList"
    />
  </div>
</template>
<script>
import CustomCalculation from '@/components/custom-calculation/index.vue';
import FlatWideTable from '@/components/flat-wide-table-dialog/index.vue';
import PanelData from '@/components/panel-data/panel-data-common';
import XMinerApiList from '@/components/panel-data/xMiner-api-list.vue';
import xTagBase from '@/components/panel-data/xtag-base';
import EventBus from '@/event-bus/EventBus.js';
import panelDataBase from '@/mixin/panel-data-base.js';
import dataModel from '@/models/panel-config-data.js';
import { nextTick } from 'vue';

/**
 * config  整体配置项
 * dataForm   初始表单的字段
 */

const XMINER = 'xMiner';
const XTAG = 'xTag';
export default {
  name: 'CommonXMultipleYPanelData',
  components: { XMinerApiList, PanelData, CustomCalculation, FlatWideTable },
  mixins: [panelDataBase, xTagBase],
  props: ['config', 'widgetInstanceId', 'dataForm', 'dataSourceTypeOptions', 'isAurora'],
  data() {
    return {
      XMINER,
      XTAG,
      result: JSON.stringify([], null, 2),
      activeColorSwitch: '#00AAFF', // 开关 打开时的颜色
      selectStyle: {
        maxWidth: '',
      },
      selectxTagStyle: {
        width: '',
      },
      dataTableList: [],
      isLoading: false,
      propertyData: this.property,
      form: {},
      xTagTextWidth: 100,

      apiLists: {}, // 若干自定义api 的  api/数据表列表
      dataSourceList: {}, // 若干个自定义api 的  数据源/数据包列表
      mappingOptions: {},
      mappingOptionsXTag: {},
      customCalculationXTag: {},
      mappingOptionsFinal: {},
      apiItem: {
        dataSourceType: '',
        dataSource: '',
        dataPackage: '',
        dataTable: '',
        apiCode: '',
        redisKey: '',
      },
      propertyFormData: [],
      datas: [],
      apis: [],
      flatWideTableParams: {
        packageCode: '',
        tableName: '',
        fieldList: '',
      },
      customCalculationParams: {
        calcList: '',
        tableName: '',
        fieldArr: '',
      },

      // 记录调用的接口，尽可能地减少api请求
      loadDataStatus: {
        dataSourceList: {},
        apiLists: {},
        mappingOptionsFinal: {},
      },

      xvueTheme: window._adoPremise.uc.theme,

      // xtag 自定义计算相关字段
      customCalculationIndex: 0,
      customCalculationCode: '',
      customCalculationType: '',
      customCalculationTitle: this.$demoi18n('panelData.commonX.addCustomCalculation'),
    };
  },
  computed: {},
  watch: {
    'form.apis': {
      handler(value) {
        this.apis = [];
        if (value && value.length) {
          value.forEach(item => {
            if (item.apiCode) {
              this.apis.push(item);
            }
          });
          this.checkOptionStatus();
        }
      },
      deep: true,
      immediate: true,
    },
  },
  created() {
    if (this.config) {
      const dataConfig = JSON.parse(JSON.stringify(this.config.config.data));
      this.form = dataConfig;
      this.loadData(dataConfig);
    }
    EventBus.$on('updatePanelPropertyFormData', propertyFormData => {
      this.updateDatas(propertyFormData);
    });
  },
  mounted() {
    // 初始化配置页面中的样例数据
    const data = this.componentsData && this.componentsData[this.widgetInstanceId];
    this.componentData = data;
    if (data && Array.isArray(data)) {
      this.updateExampleData(data);
    }
  },
  beforeUnmount() {
    EventBus.$off(`save_customCalculation_${this.widgetInstanceId}`);
  },
  unmounted() {
    EventBus.$off('updatePanelPropertyFormData');
  },
  methods: {

    // 读取配置数据
    loadData(config) {
      const { apis, customCalculationXTag, datas } = config;

      apis.forEach(apiItem => {
        const { dataSourceType, dataSource, dataPackage } = apiItem;
        if (!dataSourceType) {
          return;
        }

        // 状态对象里没有对应数据源列表
        if (!this.loadDataStatus.dataSourceList[dataSourceType]) {
          this.loadDataStatus.dataSourceList[dataSourceType] = true;
          const method = `getDataSourceList${dataSourceType}`;
          let extraConfig;
          dataModel[method](extraConfig)
            .then(list => {
              nextTick(() => {
                this.dataSourceList[dataSourceType] = list;
              });
            });
        }
        if (dataSourceType === XMINER) {
          if (!dataSource) {
            return;
          }
          if (!this.loadDataStatus.apiLists[dataSource]) {
            this.loadDataStatus.apiLists[dataSource] = true;
            const apiMethod = `getApiList${dataSourceType}`;
            dataModel[apiMethod](dataSource)
              .then(list => {
                nextTick(() => {
                  this.apiLists[dataSource] = list;
                });
              });
          }
        } else if (dataSourceType === XTAG) {
          if (!dataPackage) {
            return;
          }
          if (!this.loadDataStatus.apiLists[dataPackage]) {
            this.loadDataStatus.apiLists[dataPackage] = true;
            const apiMethod = `getApiList${dataSourceType}`;
            dataModel[apiMethod](dataPackage)
              .then(list => {
                nextTick(() => {
                  this.apiLists[dataPackage] = list;
                });
              });
          }
        } else {}
      });

      datas.forEach(dataItem => {
        const apiCode = dataItem[0].mapping;
        const apiObj = apis.find(a => a.apiCode === apiCode);
        if (apiObj) {
          const { dataSourceType, apiId, dataTable, dataPackage } = apiObj;
          if (!dataSourceType) {
            return;
          }
          if (dataSourceType === XMINER) {
            if (!apiCode || !apiId) {
              return;
            }
            if (!this.loadDataStatus.mappingOptionsFinal[apiCode]) {
              this.loadDataStatus.mappingOptionsFinal[apiCode] = true;
              const method = `getMappingOptions${dataSourceType}`;
              dataModel[method](apiId)
                .then(list => {
                  nextTick(() => {
                    this.mappingOptionsFinal[apiCode] = list;
                  });
                });
            }
          } else if (dataSourceType === XTAG) {
            if (!apiCode || !dataTable || !dataPackage) {
              return;
            }
            if (!this.loadDataStatus.mappingOptionsFinal[apiCode]) {
              this.loadDataStatus.mappingOptionsFinal[apiCode] = true;
              this.mappingOptions[apiCode] = [];
              this.mappingOptionsXTag[apiCode] = customCalculationXTag[apiCode];
              const method = `getMappingOptions${dataSourceType}`;
              dataModel[method](dataTable, dataPackage)
                .then(list => {
                  this.mappingOptions[apiCode] = list;

                  nextTick(() => {
                    this.mappingOptionsFinal[apiCode] = [
                      ...this.mappingOptionsXTag[apiCode],
                      ...this.mappingOptions[apiCode],
                    ];
                  });
                });
            }
          } else {}
        }
      });
    },

    // 增加新的API
    addAPI() {
      this.form.apis.push(JSON.parse(JSON.stringify(this.apiItem)));
    },

    // 删除选中的API
    deleteAPI(scope) {
      this.form.apis.splice(scope.$index, 1);
    },
    updateDatas(propertyFormData) {
      // 删除
      this.form.datas = this.form.datas.filter((tableData, index) => {
        const tableId = tableData[0].id;
        const item = propertyFormData.find(d => String(d.id) === String(tableId));
        return item;
      });

      // 新增
      propertyFormData.forEach((item, index) => {
        let hasDataItem = false;
        this.form.datas.forEach((tableData, tIndex) => {
          const tableId = tableData[0].id;
          if (String(item.id) === String(tableId)) {
            hasDataItem = true;
          }
        });
        if (!hasDataItem) {
          const newItem = [
            {
              id: item.id,
              field: 'api',
              apiCode: '',
              mapping: '',
              explain: 'api',
            },
            {
              id: item.id,
              field: 'x',
              apiCode: '',
              mapping: '',
              explain: this.$demoi18n('panelData.explain.horizontalAxis'),
            },
            {
              id: item.id,
              field: 'y',
              apiCode: '',
              mapping: '',
              explain: this.$demoi18n('panelData.explain.value'),
            },
            {
              id: item.id,
              field: 's',
              apiCode: '',
              mapping: '',
              explain: this.$demoi18n('word.category'),
              skipVerification: true,
            },
          ];
          this.form.datas.push(newItem);
        }
      });

      // 补充散点大小依据字段
      this.form.datas.forEach((n, i) => {
        if (propertyFormData[i]) {
          const { chartType } = propertyFormData[i];
          const hasC = n.some(n1 => n1.field === 'c');
          const cField = {
            id: propertyFormData[i].id,
            field: 'c',
            apiCode: '',
            mapping: '',
            explain: this.$demoi18n('panelData.explain.scatterSizeBasis'),
            skipVerification: true,
          };

          if (chartType === 'scatter' && !hasC) {
            n.push(cField);
          } else if (chartType !== 'scatter' && hasC) {
            n.splice(n.length - 1, 1);
          } else {}
        }
      });

      // 对y轴重新命名
      this.form.datas.forEach((tableData, index) => {
        tableData[2].field = `y${index + 1}`;
      });
      this.$forceUpdate();
    },
    optionxMinerChange(row, tableItem, tableIndex) {
      if (row.field === 'api') {
        this.tableApiChange(row, tableItem, tableIndex);
      }
    },

    // 对应轴的api改变
    tableApiChange(row, tableItem, tableIndex) {
      const apiCode = row.mapping;

      tableItem.forEach((item, index) => {
        if (index === 0) {
          return;
        }
        item.mapping = ''; // 暂时设置为空
      });
      if (!apiCode) {
        return;
      }
      const apiObj = this.apis.find(a => a.apiCode === apiCode);
      if (apiObj) {
        // 根据dataSourceType 来请求对应的下拉项字段
        if (apiObj.dataSourceType === XMINER) {
          this.setMappingOptionsXMiner(row, tableItem, tableIndex, apiObj);
        } else if (apiObj.dataSourceType === XTAG) {
          this.setMappingOptionsXTag(row, tableItem, tableIndex, apiObj);
        } else {}
      }
    },

    // 设置对应轴的映射字段
    setMappingOptionsXMiner(row, tableItem, tableIndex, apiObj) {
      this.isLoading = true;

      const key = row.mapping;
      if (this.mappingOptionsFinal[key] && this.mappingOptionsFinal[key].length) {
        this.isLoading = false;
        return;
      }

      const method = `getMappingOptions${apiObj.dataSourceType}`;
      dataModel[method](apiObj.apiId)
        .then(list => {
          list.forEach(item => {
            delete item.id;
          });
          nextTick(() => {
            this.mappingOptionsFinal[key] = list;
          });
        })
        .finally(() => {
          this.isLoading = false;
        });
    },

    /*
     * 设置对应轴的映射字段
     * 增加判断，减少请求次数
     */
    setMappingOptionsXTag(row, tableItem, tableIndex, apiObj) {
      this.isLoading = true;
      const key = row.mapping;
      if (this.mappingOptionsFinal[key] && this.mappingOptionsFinal[key].length) {
        this.isLoading = false;
        return;
      }
      this.mappingOptionsFinal[key] = [];
      this.mappingOptions[key] = [];
      this.mappingOptionsXTag[key] = [
        {
          type: 'add',
          'option_label': this.$demoi18n('panelData.commonX.addCustomCalculation'),
          'option_value': 'add_option_xTag',
        },
      ];

      const method = `getMappingOptions${apiObj.dataSourceType}`;
      dataModel[method](apiObj.dataTable, apiObj.dataPackage)
        .then(list => {
          list.forEach(item => {
            delete item.id;
          });
          this.mappingOptions[key] = list;

          nextTick(() => {
            this.mappingOptionsFinal[key] = [...this.mappingOptionsXTag[key], ...this.mappingOptions[key]];
          });
        })
        .finally(() => {
          this.isLoading = false;
        });
    },

    // 数据源类型改变  --加载数据源
    dataSourceTypeChange(row) {
      // 重置数据
      row.dataTable = '';
      row.dataPackage = '';
      row.dataSource = '';
      row.apiCode = '';
      if (this.dataSourceList[row.dataSourceType] && this.dataSourceList[row.dataSourceType].length) {
        return;
      }
      this.isLoading = true;
      const method = `getDataSourceList${row.dataSourceType}`;
      dataModel[method]()
        .then(list => {
          nextTick(() => {
            this.dataSourceList[row.dataSourceType] = list;
          });
        })
        .finally(() => {
          this.isLoading = false;
        });
    },

    // xMiner数据源改变--加载对应index的API列表
    dataSourceChange(row) {
      row.dataTable = '';
      row.apiCode = '';
      if (this.apiLists[row.dataSource] && this.apiLists[row.dataSource].length) {
        return;
      }
      this.isLoading = true;
      const apiMethod = `getApiList${row.dataSourceType}`;
      dataModel[apiMethod](row.dataSource)
        .then(list => {
          nextTick(() => {
            this.apiLists[row.dataSource] = list;
          });
        })
        .finally(() => {
          this.isLoading = false;
        });
    },

    // xMiner API表改变
    apiListChange(row) {
      const apiObj = this.apiLists[row.dataSource].find(a => String(a.option_value) === String(row.apiCode));
      if (apiObj && apiObj.option_label) {
        row.apiName = apiObj.option_label;
        row.apiId = apiObj.id;
      } else {
        row.apiName = '';
        row.apiId = '';
      }
    },

    // xTag  数据包改变--加载对应index的数据表列表
    dataPackageChange(row) {
      row.dataTable = '';
      row.apiCode = '';
      if (this.apiLists[row.dataPackage] && this.apiLists[row.dataPackage].length) {
        return;
      }
      this.isLoading = true;

      const apiMethod = `getApiList${row.dataSourceType}`;
      dataModel[apiMethod](row.dataPackage)
        .then(list => {
          nextTick(() => {
            this.apiLists[row.dataPackage] = list;
          });
        })
        .finally(() => {
          this.isLoading = false;
        });
    },

    // xTag数据表改变
    dataTableChange(row) {
      // 兼容xMiner下拉项，方便html
      row.apiName = row.dataTable;
      row.apiCode = row.dataTable;

      // 如果是xTag， 获取 mappingOptions
      if (row.dataSourceType === XTAG) {
        this.mappingOptions[row.dataTable] = [];
        const method = `getMappingOptions${row.dataSourceType}`;
        dataModel[method](row.dataTable, row.dataPackage)
          .then(list => {
            nextTick(() => {
              this.mappingOptions[row.dataTable] = list;
            });
          })
          .finally(() => {
            this.isLoading = false;
          });
      }
    },

    // 给表格数据 增加xtag自定义计算类型--增加api选项
    optionxTagChange(row, tableItem, tableIndex) {
      if (row.field === 'api') {
        this.tableApiChange(row, tableItem, tableIndex);
        return;
      }
      row.type = '';
      if (row.mapping) {
        const apiCode = tableItem[0].mapping;
        const option =
          this.customCalculationXTag[apiCode] &&
          this.customCalculationXTag[apiCode].find(o => String(o.option_value) === String(row.mapping));
        if (option) {
          row.type = option.type;
        }
      }
    },

    // 打开预览窗口
    showPreview(row) {
      if (!row.dataTable) {
        this.$message({
          message: this.$demoi18n('message.plsSelectDataTable'),
          type: 'warning',
        });
        return;
      }
      this.flatWideTableParams = {
        packageCode: row.dataPackage,
        tableName: row.dataTable,
        fieldList: this.mappingOptions[row.dataTable],
      };
      if (this.$refs.myFlatWideTable) {
        this.$refs.myFlatWideTable.openDialog();
      }
    },

    // 点击xTag 新增/编辑字段
    optionxTagClick(item, scope, tableItem, tableIndex) {
      const apiCode = tableItem[0].mapping;
      scope.row.apiCode = apiCode;
      this.curScope = scope;
      this.customCalculationParams = {
        calcList: this.mappingOptionsXTag[apiCode],
        tableName: scope.row.apiCode,
        fieldArr: this.mappingOptions[apiCode],
      };

      const index = this.mappingOptionsFinal[apiCode].findIndex(option => String(option.option_label) === String(item.option_label));

      this.customCalculationIndex = index;
      this.customCalculationType = item.type;
      if (item.type === 'add') {
        this.customCalculationTitle = this.$demoi18n('panelData.commonX.addCustomCalculation');
        this.customCalculationCode = '';
        this.openCustomCalculation();
      } else if (item.type === 'edit') {
        this.customCalculationTitle = this.$demoi18n('panelData.commonX.editCustomCalculation');
        this.customCalculationCode = item.option_label;
        this.openCustomCalculation();
      } else {}
    },
    updateMappingOptionsXTag(obj) {
      const { apiCode } = this.curScope.row;
      this.curScope.row.mapping = obj.code;
      if (obj.type === 'add') {
        this.curScope.row.type = 'edit';
        const customCalculationLength = this.mappingOptionsFinal[apiCode].filter(
          o => o.type && (o.type === 'add' || o.type === 'edit'),
        ).length;
        this.mappingOptionsFinal[apiCode].splice(customCalculationLength, 0, {
          type: 'edit',
          'option_label': obj.code,
          'option_value': obj.code,
        });
      } else if (obj.type === 'edit') {
        this.mappingOptionsFinal[apiCode].splice(obj.index, 1, {
          type: 'edit',
          'option_label': obj.code,
          'option_value': obj.code,
        });
      } else {}
    },

    // 检查数据的下拉项
    checkOptionStatus() {
      this.form.datas.forEach(dataItem => {
        const apiItem = this.apis.find(a => String(a.apiCode) === String(dataItem[0].mapping));
        if (!apiItem) {
          dataItem.forEach(item => {
            item.mapping = '';
          });
        }
      });
    },
    isCheckChange(scope) {
      const isCheck = JSON.parse(JSON.stringify(scope.row.isCheck));
      const datas = JSON.parse(JSON.stringify(this.form.datas));
      let index;
      datas.forEach((dataItem, dataIndex) => {
        const itemX = dataItem.find(d => d.field === 'x');
        itemX.isCheck = false;
        if (itemX.id === scope.row.id) {
          index = dataIndex;
        }
      });
      const item = datas[index].find(d => d.field === 'x');
      item.isCheck = isCheck;
      this.form.datas = datas;
    },

    openCustomCalculation() {
      if (this.$refs.myCustomCalculation) {
        this.$refs.myCustomCalculation.openDialog();
      }
    },

    // 设置下拉option的title属性
    setTagTitle($event) {
      if (!$event) {
        return;
      }
      const dropdownList = document.querySelectorAll('.el-select-dropdown');
      dropdownList.forEach(item => {
        const options = item.querySelectorAll('.el-select-dropdown__item');
        options.forEach(element => {
          element.setAttribute('title', element.innerText);
        });
      });
    },

    // 设置 下拉option 的最大宽度
    setMaxWidth(val) {
      // this.selectStyle.maxWidth = `${val.srcElement.clientWidth}px`;
    },

    // 设置 xtag下拉option 的最大宽度
    setXtagMaxWidth(val) {
      // const width = val.srcElement.clientWidth + 60;
      // this.selectxTagStyle.width = `${width}px`;
      // this.xTagTextWidth = width - 34;
    },

    clearTableDataMapping() {
      this.form.tableData.forEach(item => {
        item.mapping = '';
      });
    },
  },
};
</script>
<style lang="less" scoped>
.panel-data {
  .content {
    padding: 0 10px;
    .prop-form {
      .mb10 {
        margin-bottom: 10px;
      }

      :deep(.el-form-item) {
        margin-bottom: 0;
      }

      :deep(.xtag-dataTable-select) {
        width: 92px;
        padding-right: 8px;
      }
      .input-number {
        width: 80px;
        :deep(.el-input-number__decrease) {
          width: 19px;
        }
        :deep(.el-input-number__increase) {
          width: 19px;
        }
        :deep(.el-input__inner) {
          padding-left: 19px;
          padding-right: 19px;
        }
      }
      .input-number-left {
        margin-right: 25px;
      }

      .color-radio-group {
        background-color: #eeeeee;
        :deep(.el-radio-button__inner) {
          display: inline-block;
          padding: 2px 2px;
          border: 0;
          border-radius: 0;
          height: 24px;
          margin: 2px 2px;
          background: #eeeeee;
        }
        :deep(.is-active) {
          .el-radio-button__inner {
            background-color: #409eff;
          }
        }
      }
    }
    .form-datas {
      margin-top: 10px;
    }

    .table-span {
      text-align: center;
      width: 76px;
      margin-left: -5px;
    }

    .markLine {
      .switch {
        padding-top: 15px;
        .text {
          font-size: 14px;
          padding-right: 10px;
          height: 28px;
          line-height: 28px;
        }
        .value {
          display: inline-block;
          width: 150px;
          margin-left: 10px;
        }
      }
    }
  }
}
</style>

<style lang="less">
.panel-data-select-dark {
  :deep(.el-input) {
    .el-input__inner {
      border-color: #588ba8;
      color: #fff;
      background-color: #091a2d;
    }
    .el-input__icon {
      color: #588ba8;
    }
  }
}

.select-poper-dark {
  background-color: #091a2d;
  border-color: #588ba8;

  :deep(.el-scrollbar) {
    .el-select-dropdown__list {
      .el-select-dropdown__item {
        padding: 0 12px;
        height: 24px;
        line-height: 24px;
        font-size: 12px;
        color: #fff;
        background-color: #091a2d;

        .select-icon {
          padding: 0;
        }

        .select-option-slot-text {
          display: inline-block;

          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          color: #178ddf;
        }
        .select-option-slot-icon {
          display: inline-block;
          vertical-align: top;
        }
      }
      .hover {
        background-color: #102e4f;
      }
    }
  }
  :deep(.popper__arrow) {
    border-bottom-color: #588ba8;
    &::after {
      border-bottom-color: #091a2d !important;
    }
  }
}

.select-poper-light {
  :deep(.el-scrollbar) {
    .el-select-dropdown__list {
      .el-select-dropdown__item {
        padding: 0 12px;
        height: 24px;
        line-height: 24px;
        font-size: 12px;

        .select-icon {
          padding: 0;
        }

        .select-option-slot-text {
          display: inline-block;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
        }
        .select-option-slot-icon {
          display: inline-block;
          vertical-align: top;
        }
      }
    }
  }
}
</style>
